package cn.xyafu.controller;

import cn.xyafu.po.Comment;
import cn.xyafu.po.Lost;
import cn.xyafu.po.Page;
import cn.xyafu.po.User;
import cn.xyafu.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@Transactional
public class CommentController {
    @Autowired
    private CommentService commentService;

    /**
     * 查询所有相关评论（lid）
     */
    @RequestMapping("/allComments")
    public String findAllCommentsByLid(HttpSession session, HttpServletRequest req, Model model){
        //当前lost的lid
        Integer lid = ((Lost)session.getAttribute("onelost")).getLid();

        //分页显示评论
        Page page = (Page) session.getAttribute("comment_page");

        //判断是否为首次点开或者首页或其他页
        if (page == null) {      //首次点开
            page = new Page(1, 5);
            page.setTotal(this.commentService.countCommentByLid(lid));
        } else {
            String str = req.getParameter("set");       //获取翻页操作
            int nowPage = page.getStart();              //当前页码
            if ("add".equals(str)) {                 //下一页
                if (page.isHasNext()) {          //已是尾页

                } else {
                    page.setStart(nowPage + 1);
                }
            } else if ("sub".equals(str)) {           //上一页
                if (!page.isHasPreviouse()) {             //已是首页

                } else {
                    page.setStart(nowPage - 1);
                }
            } else if ("top".equals(str)) {           //首页
                page.setStart(1);
            } else if ("bottom".equals(str)) {        //尾页
                page.setStart(page.getTotalPage());
            }
        }
        List<Comment> comments = null;
        Integer start = (page.getStart() - 1) * page.getCount();
        Integer end = page.getCount();

        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("start",start);
        map.put("end",end);
        map.put("lid",lid);

        //分页查找当前lost相关评论
        comments = this.commentService.findAllByLid(map);

//        System.out.println(comments);

        session.setAttribute("comments",comments);
//        model.addAttribute("comments",comments);
        session.setAttribute("comment_page", page);

        return "showmsg";
    }

    /**
     * 添加评论（lid）
     */
    @RequestMapping("/addComment")
    public void addComment(HttpSession session, Comment comment, HttpServletResponse response) throws IOException {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
//        System.out.println("comment:"+comment);
        SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
        comment.setCdate(sdf.format(new Date()));
        User user = (User)session.getAttribute("USER_SESSION");
        comment.setUser(user);
        this.commentService.addComment(comment);
        response.getWriter().print("<script>alert('感谢留言！');window.location.href='/Lost_ssm/showLost?lostId="+comment.getLid()+"&page=page'</script>");
    }


}
